import axios from 'axios'
import { UniAdapter } from "uniapp-axios-adapter";

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';

const instance = axios.create({
    baseURL:'http://localhost:18080',
    timeout:5000,
    headers:{},
    adapter:UniAdapter
    
})

instance.interceptors.request.use(config => {
    if (uni.getStorageSync('admin-token')) {
        config.headers['Authorization'] = 'Bearer '+uni.getStorageSync('admin-token')
    }else{
        uni.navigateTo({url:'/pages/index/login'})
    }
    if (config.url === '/app/login') {
        config.data = {
            ...config.data,
            clientId:'428a8310cd442757ae699df5d894f051',
            grantType:'password'
        } 
    }else{
        config.data = {
            ...config.data
        }
    }
    
    return config
})
instance.interceptors.response.use(response => {
    console.log(response);
    if (response.data.code === 403) {
        uni.navigateTo({url:'/pages/index/login'})
    }
    return response;
    
})

// axios.defaults.adapter = function(config) {
// 	return new Promise((resolve, reject) => {
// 		let settle = require('axios/lib/core/settle');
// 		let buildURL = require('axios/lib/helpers/buildURL');
// 		let buildFullPath = require('axios/lib/core/buildFullPath');
// 		let fullurl = buildFullPath(config.baseURL, config.url);
// 		uni.request({
// 			method: config.method.toUpperCase(),
// 			url: buildURL(fullurl, config.params, config.paramsSerializer),
// 			header: config.headers,
// 			data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
// 			dataType: config.dataType,
// 			responseType: config.responseType,
// 			sslVerify: config.sslVerify,
// 			complete: function complete(response) {
// 				response = {
// 					data: response.data,
// 					status: response.statusCode,
// 					errMsg: response.errMsg,
// 					header: response.header,
// 					config: config
// 				};
// 				settle(resolve, reject, response);
// 			},
// 		});
// 	})
// }

export default instance;